﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;




namespace WindowsFormsApplication1
{
    public partial class FormUtilisateurs : Form
    {
        private BindingSource bindingSource1 = new BindingSource();
        private SqlDataAdapter dataAdapter = new SqlDataAdapter();
        


        public FormUtilisateurs()
        {
            InitializeComponent();
            dataGridView1.Dock = DockStyle.Fill;

            
        }

         

        private void FormUtilisateurs_Load(object sender, EventArgs e)
        {
            
            // Lie le DataGridView au BindingSource
            // Et charge les donnée de la BDD
               dataGridView1.DataSource = bindingSource1;
               GetData("select * from Utilisateur");
    
            //Empecher la selection multiple
               dataGridView1.MultiSelect = false;
            
        }

        private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            int colonne = e.ColumnIndex;
            int ligne = e.RowIndex;

           
        }


       private void Send_Click(object sender, EventArgs e)
        {

            if (!textBox1.Text.Equals("") && !textBox2.Text.Equals("") && !comboBox1.Text.Equals(""))
            {
                
                // Mis à jour de la bdd avec les changements de l'user. 
                SetData("insert into Utilisateur([username],[password],type) VALUES ('"+ textBox1.Text + "','" + textBox2.Text + "','" + comboBox1.Text + "')");
                dataAdapter.Update((DataTable)bindingSource1.DataSource);
                GetData(dataAdapter.SelectCommand.CommandText);
                textBox1.Text = "";
                textBox2.Text = "";
                comboBox1.Text = "";
            }
            else
            {
                MessageBox.Show("Veuillez remplir les 3 champs SVP !");
            }
       }

        private void GetData(string selectCommand)
        {
            try
            {
                // Spécifie un chemin de connexion
                String connectionString = @"Data Source=.\SQLEXPRESS;AttachDbFilename='|datadirectory|\Database1.mdf';Integrated Security=True;User Instance=True";

                // Créé un new Data Adapter basé sur une commande spécifiée.
                dataAdapter = new SqlDataAdapter(selectCommand, connectionString);

                // Créé un "Buider Command" pour générer (update, insert, delete) des commandes
                // établis par "selectCommand"
                // utilisé pour mettre à jour la BDD.
                SqlCommandBuilder commandBuilder = new SqlCommandBuilder(dataAdapter);

                // Créé une nouvelle dataTable et la lie au "BindingSource".
                DataTable table = new DataTable();
                table.Locale = System.Globalization.CultureInfo.InvariantCulture;
                dataAdapter.Fill(table);
                bindingSource1.DataSource = table;

                // Redimensionne le "DataGridView" en fonction du contenu récemment chargé.
                dataGridView1.AutoResizeColumns(
                    DataGridViewAutoSizeColumnsMode.AllCellsExceptHeader);
               
            }
            catch (SqlException)
            {
                MessageBox.Show("Erreur SQL");
            }
        }

        public DataGridView getDataGridView()
        {
            return this.dataGridView1;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        


       private void SetData(string selectCommand)
        {
            try
            {
                // Spécifie un chemin de connexion
                String connectionString = @"Data Source=.\SQLEXPRESS;AttachDbFilename='|datadirectory|\Database1.mdf';Integrated Security=True;User Instance=True";
                SqlCommand cmd = new SqlCommand();
                cmd.CommandText = selectCommand;
                SqlConnection cnx=new SqlConnection(connectionString);
                cnx.Open();
                cmd.Connection = cnx;
                cmd.ExecuteNonQuery();
                cnx.Close();
                

            }
            catch (SqlException)
            {
                MessageBox.Show("Erreur Sql");
            }
        }

       private void button3_Click(object sender, EventArgs e)
       {
           if (dataGridView1.SelectedRows.Count > 0)
           {
                if (textBox1.Text.Equals("") && textBox2.Text.Equals("") && comboBox1.Text.Equals("")){
                   MessageBox.Show("Veuillez remplir au moins un champs pour le modifier, SVP");
               }

               if (!textBox1.Text.Equals(""))
               {
                   SetData("update Utilisateur set [username] ='" + textBox1.Text + "'where id_utilisateur=" + (dataGridView1.CurrentRow.Index + 1));
                   dataAdapter.Update((DataTable)bindingSource1.DataSource);
                   GetData(dataAdapter.SelectCommand.CommandText);
                   textBox1.Text = "";
               }
               if (!textBox2.Text.Equals(""))
               {
                   SetData("update Utilisateur set [password] ='" + textBox2.Text + "'where id_utilisateur=" + (dataGridView1.CurrentRow.Index + 1));
                   dataAdapter.Update((DataTable)bindingSource1.DataSource);
                   GetData(dataAdapter.SelectCommand.CommandText);
                   textBox2.Text = "";
               }
                  
               if(!comboBox1.Text.Equals(""))
               {
                   SetData("update Utilisateur set type ='" + comboBox1.Text + "'where id_utilisateur=" + (dataGridView1.CurrentRow.Index + 1));
                   dataAdapter.Update((DataTable)bindingSource1.DataSource);
                   GetData(dataAdapter.SelectCommand.CommandText);
                   comboBox1.Text = "";
               }

               
           }
           else
           {
               MessageBox.Show("Veuillez Sélectionner une ligne à modifier, SVP");
           }
       }

       private void button4_Click_1(object sender, EventArgs e)
       {
           if (dataGridView1.SelectedRows.Count > 0)
           {
               //SetData("delete from Utilisateur where id_utilisateur=" + (dataGridView1.CurrentRow.Index+1));
               System.Console.WriteLine(dataGridView1.CurrentRow.Cells[0].Value);
               SetData("delete from Utilisateur where id_utilisateur=" + (dataGridView1.CurrentRow.Cells[0].Value));
               dataAdapter.Update((DataTable)bindingSource1.DataSource);
               GetData(dataAdapter.SelectCommand.CommandText);
           }
           else
           {
               MessageBox.Show("Veuillez Sélectionner une ligne à supprimer, SVP");
           }
       }

       private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
       {
           if (!char.IsControl(e.KeyChar) && char.IsDigit(e.KeyChar))
           {
               e.Handled = true;
           }

       }

       private int mBackImageAlpha = 100;

       /// <summary> 

       /// Back Image Alpha 0-255 

       /// </summary> 

       [Category("Appearance"),

        DefaultValue(255),

        Description("Back Image Alpha 0-255")]

       public int BackImageAlpha
       {

           get { return mBackImageAlpha; }

           set
           {

               mBackImageAlpha = value;

               if (mBackImageAlpha < 0)

                   mBackImageAlpha = 0;

               if (mBackImageAlpha > 255)

                   mBackImageAlpha = 255;

               this.Invalidate();

           }

       }



       Image mBackImage = null;

       /// <summary> 

       /// BackImage 

       /// </summary> 

       [Category("Appearance"), DefaultValue(null), Description("BackImage")]

       public Image BackImage
       {

           get { return mBackImage; }

           set
           {

               mBackImage = value;

               this.Invalidate();

           }

       }



       private void DrawBackGround(Graphics g)
       {

           Rectangle r = this.ClientRectangle;



           ColorMatrix cm = new ColorMatrix();

           ImageAttributes ia = new ImageAttributes();

           cm.Matrix33 = (1f / 255) * BackImageAlpha;

           ia.SetColorMatrix(cm, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);



           #region draw Back Image

           {

               if (this.BackImage != null)
               {

                   g.DrawImage(this.BackImage, r, 0, 0, this.BackImage.Width, this.BackImage.Height, GraphicsUnit.Pixel, ia);

               }

           }

           #endregion

       }



       #region overrided propertys & functions

       protected override void OnPaint(PaintEventArgs e)
       {

           base.OnPaint(e);

           e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;

           e.Graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;

           DrawBackGround(e.Graphics);

       }

       #endregion




    }


}